function getPollInterval()
{
	var pollInterval = localStorage.getItem('pollInterval');
	if(!pollInterval)
	{
		pollInterval = 15; //min
		localStorage.setItem('pollInterval', pollInterval);
	}
	return pollInterval;
}

function updateBadgeCounter()
{
	window.clearTimeout();
	setLoadingBadge();
	$.ajax({
		url: "https://www.unwired.com.au/myaccount/usage.php",
		type: "GET",
		data: "",
		dataType: "html",
		success: function (html){
			var usageProgress = getUsageProgress(html);
			
			if(!usageProgress.error)
			{
				var progressPercentage = usageProgress.progressPercentage;
				var dayPercentage = usageProgress.dayPercentage;
			
				chrome.browserAction.setBadgeBackgroundColor({color: (progressPercentage > dayPercentage)?[255, 0, 0, 255]:[0, 255, 0, 255]});
				chrome.browserAction.setBadgeText({text: Math.round(progressPercentage) + '%'});
			}
			else
			{
				setEmptyBadge();
			}
			
			scheduleUpdateBadgCounterRequest();
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			setEmptyBadge();
			scheduleUpdateBadgCounterRequest();
		}
	});
}

function scheduleUpdateBadgCounterRequest()
{
	window.setTimeout(updateBadgeCounter, 1000 * 60 * getPollInterval());
}

function setEmptyBadge()
{
	chrome.browserAction.setBadgeBackgroundColor({color: [127, 127, 127, 255]});
	chrome.browserAction.setBadgeText({text: '?'});
}

function setLoadingBadge()
{
	chrome.browserAction.setBadgeBackgroundColor({color: [127, 127, 127, 255]});
	chrome.browserAction.setBadgeText({text: '...'});
}

function getUsageProgress(html)
{
	var usageMax = null;
	$(".usageTable:first tr", html).each(function(index){
		if(index == 1)
		{
			usageMax = parseFloat($(this).html().match(/\d+\.\d+/));
			if($(this).html().indexOf('GB') > -1)
			{
				usageMax = usageMax * 1000;
			}
		}
	});
	var usageValue = null;
	$(".usageTable:last tr", html).each(function(index){
		if(index == 3)
		{
			usageValue = parseFloat($(this).html().match(/\d+\.\d+/));
			if($(this).html().indexOf('GB') > -1)
			{
				usageValue = usageValue * 1000;
			}
		}
	});

	if(usageMax && usageValue)
	{
		var progressPercentage = 100 * usageValue / usageMax;
		var currentPeriod = $("dt:first a", html).html();
		var dayPercentage = getDayPercentage(currentPeriod);
		
		return {
			progressPercentage: progressPercentage,
			dayPercentage: dayPercentage
		};
	}
	else
	{
		return {
			error: 'value unfound'
		};
	}
}

function getDayPercentage(currentPeriod)
{
	var startDay = Number(currentPeriod.substring(0, currentPeriod.indexOf('-')));
	var endPeriod = currentPeriod.substring(currentPeriod.indexOf(' - ')).replace(' - ','');
	var endDay = Number(endPeriod.substring(0, endPeriod.indexOf('-')));
	
	var now = new Date();
	var isLastMonth = now.getDay() >= startDay;
	var isJanuary = isLastMonth === false && now.getMonth() === 0;
	var startDate = isJanuary?new Date(now.getFullYear() - 1, 11, startDay):new Date(now.getFullYear(), now.getMonth() + (isLastMonth?0:-1), startDay);
	var endDate = new Date(now.getFullYear(), now.getMonth() + (isLastMonth?1:0), endDay);
	
	var nbTotalDays = nbDaysBetween(startDate, endDate);
	var nbRemainingDays = nbDaysBetween(now, endDate);
	
	return 100 * ((nbTotalDays - nbRemainingDays) / nbTotalDays);
}

function nbDaysBetween(startDate, endDate)
{
	// The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24;

    // Convert both dates to milliseconds
    var date1_ms = startDate.getTime();
    var date2_ms = endDate.getTime();

    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms);
    
    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY);
}